<?php
/**
 * Copyright (c) 2009, Jacek Karczmarczyk
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the author nor the names of its contributors may be
 *   used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * PHP Version 5
 *
 * @package Larchana_View
 * @version 0.1
 * @author Jacek Karczmarczyk <jacek@karczmarczyk.pl>
 */




/**
 * Example usage:
 *
 * <code>
 * <?php
 *       $headers = array(
 *           'name'=>array('label'=>'Client name', 'sortable'=>true),
 *           'address'=>array('label'=>'Address', 'escape'=>false, 'helper'=>'compileAddress')
 *       );
 *
 *       $data = array( // $foo->loadFromDatabase()
 *           array('name'=>'Company 1', 'address'=>"Street\nCity\nCountry", '__class'=>'special'),
 *           array('name'=>'Do>It', 'address'=>"Street\nCity\nCountry"),
 *       );
 *
 *       $this->htmlSortableTable($headers, $data, array('id'=>'table', 'class'=>'itemlist'));
 * ?>
 * </code>
 *
 * @todo Allow to create the table with multiline header
 * Proposed usage:
 * <code>
 * $headers = array(
 *     'name'=>array(
 *         'label'=>'Name',
 *         'class'=>'name', // the class of the firstname column will be "name firstname"
 *         'sortable'=>N.A., // not applicable
 *         'escape'=>N.A., // not applicable
 *         'helper'=>N.A., // not applicable
 *         'sub'=>array(
 *             'firstname'=>array('label'=>'First name', 'sortable'=>true, 'class'=>'firstname'),
 *             'lastname'=>array('label'=>'Last name', 'escape'=>false, 'sortable'=>true)
 *         )
 *     )
 * )
 * </code>
 *
 */
class Larchana_View_Helper_HtmlSortableTable extends Zend_View_Helper_HtmlElement
{
	/**
	 * @var array Array of headers definitions
	 */
	protected $_headers;

	/**
	 * @var array Items to display
	 */
	protected $_items;

	/**
	 * Creates the HTML code of the table filled with user data
	 *
	 * Items to display should be iterable, it can be array, ArrayObject etc
	 * Headers are allowed to have the following options:
	 * - label (string, required) - text of header
	 * - sortable (boolean, optional, default false) - true if column is sortable, the header will became a link to sort up or down
	 * - escape (boolean, optional, default true) - if false the output wont be escaped (ie if created by a helper)
	 * - helper (string, optional) - name of the helper used to generate the cell content
	 * - class (string, optional) - the CSS class of the header and each cell in the column
	 * Data items are allowed to have "__class" attribute which will became the CSS class of the data row
	 * The name of the _GET parameter used for sorting is "order"
	 *
	 * @param array $headers Header definitions
	 * @param array $items Array of arrays with data to display
	 * @param array $options Additional options such as HTML attribs (id, class), caption, selectable
	 * @return string Html code
	 */
	public function htmlSortableTable(array $headers, $items, array $options = null)
	{
		$this->_headers = $headers;
		$this->_items = $items;

		$xhtml = '';

		// Start the table, add the CAPTION tag if available
		//
		$xhtml .= '<table'.$this->_htmlAttribs(isset($options['attribs']) ? $options['attribs'] : array()).'>'.self::EOL;
		if (isset($options['caption']))
			$xhtml .= '<caption>'.$this->view->escape($this->view->translate($options['catpion'])).'</caption>'.self::EOL;

		// Render headers
		//
		$xhtml .= '<thead><tr>'.self::EOL;
		if (isset($options['selectable']) && $options['selectable']) $xhtml .= '<th></th>'.self::EOL;
		foreach($headers as $name=>$header) $xhtml .= $this->_getHeader($name).self::EOL;
		$xhtml .= '</tr></thead>'.self::EOL;

		// Render body
		//
		$xhtml .= '<tbody>'.self::EOL;
		foreach($items as $item) $xhtml .= $this->view->htmlTableRow($headers, $item, $options);
		$xhtml .= '</tbody>'.self::EOL;

		// Close the TABLE tag
		//
		$xhtml .= '</table>'.self::EOL;
		return $xhtml;
	}

	/**
	 * Creates the HTML code of the TH element
	 *
	 * @param string $name Name of the header
	 * @return string HTML code of the TH element (including the TH tag)
	 */
	protected function _getHeader($name)
	{
		$header = $this->_headers[$name];

		$order = isset($_GET['order']) ? $_GET['order'] : '';
		$field = preg_replace('/-(a|de)sc$/', '', $order);
		$dir = substr($order, strlen($field)+1);

		// Add sort class to header (if applicable)
		//
		if (isset($header['sortable']) && $header['sortable'] && $field === $name)
		{
			if (!isset($header['class'])) $header['class'] = '';
			$header['class'] .= $dir == 'desc' ? ' sort sort-desc' : ' sort sort-asc';
		}

		// Start the TH tag with attributes
		//
		$xhtml = '<th';
		if (isset($header['class'])) $xhtml .= $this->_htmlAttribs(array('class'=>trim($header['class'])));
		$xhtml .= '>';

		// Create the content of the header, if the column is sortable header content will
		// became the link to sort up or down
		//
		$content = $this->view->escape($this->view->translate($header['label']));
		if (isset($header['sortable']) && $header['sortable'])
		{
			$args = $_GET;
			$args['order'] = $name.'-'.(($field == $name && $dir == 'asc') ? 'desc' : 'asc');
			$content = '<a href="'.$this->view->escape('?'.http_build_query($args)).'">'.$content.'</a>';
		}
		$xhtml .= $content;

		// Close the TH tag
		//
		$xhtml .= '</th>';
		
		return $xhtml;
	}
}
